package com.haixiaoke.saas.house.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.apartment.domain.HousingAllocation;
import com.haixiaoke.saas.apartment.domain.ServiceFacilities;
import com.haixiaoke.saas.apartment.service.IHousingAllocationService;
import com.haixiaoke.saas.apartment.service.IServiceFacilitiesService;
import com.haixiaoke.saas.bill.domain.HouseBill;
import com.haixiaoke.saas.bill.domain.ProprietorBill;
import com.haixiaoke.saas.bill.service.IHouseBillService;
import com.haixiaoke.saas.bill.service.IProprietorBillService;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.constant.HttpStatus;
import com.haixiaoke.saas.common.constant.OrderConstants;
import com.haixiaoke.saas.common.core.page.PageDomain;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.core.page.TableSupport;
import com.haixiaoke.saas.common.enums.HouseStateEnum;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.contract.domain.Proprietor;
import com.haixiaoke.saas.contract.service.IProprietorService;
import com.haixiaoke.saas.house.domain.*;
import com.haixiaoke.saas.house.mapper.HouseMapper;
import com.haixiaoke.saas.house.service.*;
import com.haixiaoke.saas.lock.service.IHouseLockService;
import com.haixiaoke.saas.order.domain.Order;
import com.haixiaoke.saas.order.service.IOrderService;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import com.haixiaoke.saas.user.service.IUserConsumerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 房屋信息Service业务层处理
 *
 * @author panda
 * @date 2023-10-18
 */
@Slf4j
@Service
public class HouseServiceImpl implements IHouseService {
    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private ISubHouseService iSubHouseService;
    @Autowired
    private IHousingAllocationService iHousingAllocationService;
    @Autowired
    private IHouseFacilitiesItemService iHouseFacilitiesItemService;
    @Autowired
    private IHouseOperatingRecordService iHouseOperatingRecordService;
    @Autowired
    private IEstateService iEstateService;
    @Autowired
    private IServiceFacilitiesService iServiceFacilitiesService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IBizUserBusinessService bizUserBusinessService;
    @Autowired
    private IProprietorBillService propertiesBillService;
    @Autowired
    private IHouseBillService houseBillService;
    @Autowired
    private IProprietorBillService proprietorBillService;
    @Autowired
    private IProprietorService proprietorService;
    @Autowired
    private IHouseLockService houseLockService;


    /**
     * 查询房屋信息
     *
     * @param houseId 房屋信息主键
     * @return 房屋信息
     */
    @Override
    public House selectHouseByHouseId(String houseId) {
        House house = houseMapper.selectHouseByHouseId(houseId);
        HousingAllocation housingAllocation = iHousingAllocationService.selectHousingAllocationByHouseId(houseId);
        List<HouseFacilitiesItem> facilitiesItemList = iHouseFacilitiesItemService.selectHouseFacilitiesItemByHouseId(houseId);
        List<SubHouse> subordinateHouseList = iSubHouseService.selectSubordinateHouseByHouseId(houseId);
        house.setHousingAllocation(housingAllocation);
        house.setFacilitiesItemList(facilitiesItemList);
        house.setSubHouseList(subordinateHouseList);
        return house;
    }

    @Override
    public House selectHouseInfoByHouseId(String houseId) {
        return houseMapper.selectHouseInfoByHouseId(houseId);
    }

    /**
     * 根据房屋id查询房屋信息
     *
     * @param houseId 房屋信息主键
     * @return 房屋信息
     */
    @Override
    public House selectHouseById(String houseId) {
        return houseMapper.selectHouseByHouseId(houseId);
    }

    /**
     * 查询房屋信息列表
     *
     * @param house 房屋信息
     * @return 房屋信息
     */
    @Override
    public List<House> selectHouseList(House house) {
        return houseMapper.selectHouseList(house);
    }

    /**
     * 新增房屋信息
     *
     * @param house 房屋信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertHouse(House house) {
        String houseId = "H" + System.currentTimeMillis() + RandomUtils.nextInt(10000, 100000);
        house.setHouseId(houseId);
        packagingData(house);
        house.setCreateTime(DateUtils.getNowDate());

        // 默认当天最晚时间
        if (house.getLatestPaymentDate() != null) {
            DateTime dateTime = DateUtil.endOfDay(house.getLatestPaymentDate());
            // endOfDay方法会将时间毫秒值格式化为999，mysql数据库时间毫秒值会四舍五入 自动加一秒，所以需要减去1秒
            house.setLatestPaymentDate(DateUtil.offset(dateTime, DateField.SECOND, -1));
        }


        int i = houseMapper.insertHouse(house);
        // 记录操作记录
        if (i != 0) {
            HouseOperatingRecord record = new HouseOperatingRecord();
            record.setHouseId(houseId);
            record.setOperatingRecordContent("创建了房屋信息");
            record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
            record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
            record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
            record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
            iHouseOperatingRecordService.insertHouseOperatingRecord(record);
        }

      /*  //新增子房间
        if (i != 0 && HouseConstants.SHARE_FLAT_YES.equals(house.getShareFlatType())) {
            List<SubHouse> subordinateHouseList = house.getSubHouseList();
            if (CollectionUtil.isNotEmpty(subordinateHouseList)) {
                BigDecimal subordinateArea = subordinateHouseList.stream()
                        .map(SubHouse::getSubHouseArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                //flag = -1，表示house.getHouseArea()小于subordinateArea。
                //flag =0，表示house.getHouseArea()等于subordinateArea。
                //flag =1，表示house.getHouseArea()大于subordinateArea。
                if (house.getHouseArea().compareTo(subordinateArea) == -1) {
                    throw new ServiceException("子房间的面积总和不能超过房间的面积！");
                }
                for (SubHouse subordinateHouse : subordinateHouseList) {
                    BeanUtil.copyProperties(house, subordinateHouse);
                    String subordinateHouseId = "S" + System.currentTimeMillis() + RandomUtils.nextInt(10000, 100000);
                    subordinateHouse.setSubHouseId(subordinateHouseId);
                    subordinateHouse.setFullAddress(house.getFullAddress());
                    HouseOperatingRecord record = new HouseOperatingRecord();
                    record.setHouseId(houseId);
                    record.setSubHouseId(subordinateHouseId);
                    record.setOperatingRecordContent("创建了房屋信息");
                    record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
                    record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
                    record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
                    record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
                    iHouseOperatingRecordService.insertHouseOperatingRecord(record);
                }
//            BeanUtil.copyProperties(house,subordinateHouseList);
                iSubHouseService.insertBatchSubordinateHouse(subordinateHouseList);
            }
        }*/
        //新增房屋设施
        List<HouseFacilitiesItem> facilitiesItemList = house.getFacilitiesItemList();
        if (i != 0 && CollectionUtil.isNotEmpty(facilitiesItemList)) {
            List<Long> facilitiesIds = facilitiesItemList.stream().map(HouseFacilitiesItem::getFacilitiesId).collect(Collectors.toList());
            List<ServiceFacilities> serviceFacilities = iServiceFacilitiesService.selectBatchHouseFacilitiesByFacilitiesId(facilitiesIds);
            Map<Long, ServiceFacilities> collect = serviceFacilities.stream().collect(Collectors.toMap(ServiceFacilities::getFacilitiesId, HouseFacilities -> HouseFacilities));
            facilitiesItemList.forEach(x -> {
                x.setHouseId(houseId);
                x.setCreateBy(house.getCreateBy());
                x.setCreateTime(house.getCreateTime());
                ServiceFacilities facilities = collect.get(x.getFacilitiesId());
                x.setFacilitiesName(facilities.getFacilitiesName());
            });
            iHouseFacilitiesItemService.insertHouseFacilitiesItemList(facilitiesItemList);
        }
        propertiesBillService.insertProprietorBillByHouse(house.getHouseId());

        return i;
    }

    private void packagingData(House house) {

        if (house.getHouseArea().compareTo(BigDecimal.ZERO) <= 0) {
            throw new ServiceException("面积需大于0");
        }

        if (HouseStateEnum.COOPERATION_TYPE_AGENCY.equals(house.getCooperationType())) {
            if (house.getChargeType().equals(HouseStateEnum.CHARGE_TYPE_BILL.getValue())) {
                if (house.getServiceCharge().scale() > 1) {
                    throw new ServiceException("账单服务费最多小数点后一位");
                }
                if (house.getServiceCharge().compareTo(new BigDecimal("100")) > 0) {
                    throw new ServiceException("账单服务费比例不能大于100");
                }
            } else {
                if (house.getFeeAmount().scale() > 2) {
                    throw new ServiceException("账单服务费最多小数点后两位");
                }
                if (house.getFeeAmount().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new ServiceException("费用金额需大于0元");
                }
            }
        }
        if (house.getCheckInNumber() == 0) {
            throw new ServiceException("可住人数需大于0");
        }
        BizUserBusiness userBusiness = bizUserBusinessService.selectBizUserBusinessByUserId(house.getHouseManagerId(), house.getTenantId());
        if (ObjectUtil.isEmpty(userBusiness)) {
            throw new ServiceException("房管家不存在");
        }
        Proprietor proprietor = proprietorService.selectProprietorByConUserId(house.getProprietorUserId());
        if (ObjectUtil.isEmpty(proprietor)) {
            throw new ServiceException("业主不存在");
        }
        house.setHouseManagerName(userBusiness.getUserName());
        house.setHouseManagerPhone(userBusiness.getPhonenumber());
        house.setProprietorName(proprietor.getProprietorName());
        Estate estate = iEstateService.selectEstateByEstateId(house.getEstateId());
        house.setPremisesAddress(estate.getPremisesAddress());

        String premisesAddress = house.getEstateName() + house.getBuildingName() + "栋" + house.getUnitName() + "单元" + house.getRoomNumber() + "房";
        String fullAddress = estate.getProvinceName() + estate.getCityName() + estate.getDistrictName() + estate.getStreetName()
                + premisesAddress;
        house.setPremisesAddress(premisesAddress);
        house.setFullAddress(fullAddress);
        house.setProvinceId(estate.getProvinceId());
        house.setProvinceName(estate.getProvinceName());
        house.setCityId(estate.getCityId());
        house.setCityName(estate.getCityName());
        house.setDistrictId(estate.getDistrictId());
        house.setDistrictName(estate.getDistrictName());
        house.setStreetId(estate.getStreetId());
        house.setStreetName(estate.getStreetName());
        house.setCommunityId(estate.getCommunityId());
        house.setCommunityName(estate.getCommunityName());
    }

    /**
     * 修改房屋信息
     *
     * @param house 房屋信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateHouse(House house) {

        House byHouseId = houseMapper.selectHouseByHouseId(house.getHouseId());
        if (!TenantContext.getTenantId().equals(byHouseId.getTenantId())) {
            throw new ServiceException("异常操作！");
        }
        packagingData(house);

        // 房管员变更
        if (!byHouseId.getHouseManagerId().equals(house.getHouseManagerId())) {
            houseLockService.updateHouseManager(house.getHouseId(), house.getHouseManagerId());
        }


        house.setUpdateTime(DateUtils.getNowDate());
        int i = houseMapper.updateHouse(house);
        if (i != 0) {
            HouseOperatingRecord record = new HouseOperatingRecord();
            record.setHouseId(house.getHouseId());
            record.setOperatingRecordContent("编辑了房屋信息");
            record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
            record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
            record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
            record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
            iHouseOperatingRecordService.insertHouseOperatingRecord(record);
        }

       /* //编辑子房间
        if (i != 0 && HouseConstants.SHARE_FLAT_YES.equals(house.getShareFlatType())) {
            List<SubHouse> subordinateHouseList = house.getSubHouseList();
            if (CollectionUtil.isNotEmpty(subordinateHouseList)) {
                BigDecimal subordinateArea = subordinateHouseList.stream()
                        .map(SubHouse::getSubHouseArea).reduce(BigDecimal.ZERO, BigDecimal::add);
                //flag = -1，表示house.getHouseArea()小于subordinateArea。
                //flag =0，表示house.getHouseArea()等于subordinateArea。
                //flag =1，表示house.getHouseArea()大于subordinateArea。
                if (house.getHouseArea().compareTo(subordinateArea) == -1) {
                    throw new ServiceException("子房间的面积总和不能超过房间的面积！");
                }
                List<SubHouse> updateList = subordinateHouseList.stream().filter(x -> x.getSubHouseId() != null).collect(Collectors.toList());
                List<SubHouse> insertList = subordinateHouseList.stream().filter(x -> x.getSubHouseId() == null).collect(Collectors.toList());
                for (SubHouse subordinateHouse : insertList) {
                    BeanUtil.copyProperties(house, subordinateHouse);
                    String subordinateHouseId = "H" + System.currentTimeMillis() + RandomUtils.nextInt(10000, 100000);
                    subordinateHouse.setSubHouseId(subordinateHouseId);
                    subordinateHouse.setFullAddress(house.getFullAddress());
                    HouseOperatingRecord record = new HouseOperatingRecord();
                    record.setHouseId(house.getHouseId());
                    record.setSubHouseId(subordinateHouseId);
                    record.setOperatingRecordContent("创建了房屋信息");
                    record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
                    record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
                    record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
                    record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
                    iHouseOperatingRecordService.insertHouseOperatingRecord(record);
                }
                for (SubHouse subordinateHouse : updateList) {
                    BeanUtil.copyProperties(house, subordinateHouse);
                    HouseOperatingRecord record = new HouseOperatingRecord();
                    record.setHouseId(house.getHouseId());
                    record.setSubHouseId(subordinateHouse.getSubHouseId());
                    record.setOperatingRecordContent("编辑了房屋信息");
                    record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
                    record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
                    record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
                    record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
                    iHouseOperatingRecordService.insertHouseOperatingRecord(record);
                }
                String[] subordinateHouseIds = updateList.stream().map(SubHouse::getSubHouseId).toArray(String[]::new);
                iSubHouseService.deleteSubordinateHouseBySubordinateHouseIds(subordinateHouseIds);
                iSubHouseService.insertBatchSubordinateHouse(insertList);
                iSubHouseService.updateBatchSubordinateHouse(updateList);
            }

        }*/

        //编辑房屋设施
        List<HouseFacilitiesItem> facilitiesItemList = house.getFacilitiesItemList();
        if (CollectionUtil.isNotEmpty(facilitiesItemList)) {
            List<Long> facilitiesIds = facilitiesItemList.stream().map(HouseFacilitiesItem::getFacilitiesId).collect(Collectors.toList());
            List<ServiceFacilities> serviceFacilities = iServiceFacilitiesService.selectBatchHouseFacilitiesByFacilitiesId(facilitiesIds);
            Map<Long, ServiceFacilities> collect = serviceFacilities.stream().collect(Collectors.toMap(ServiceFacilities::getFacilitiesId, HouseFacilities -> HouseFacilities));
            facilitiesItemList.forEach(x -> {
                x.setHouseId(house.getHouseId());
                x.setCreateBy(house.getUpdateBy());
                x.setCreateTime(house.getUpdateTime());
                ServiceFacilities facilities = collect.get(x.getFacilitiesId());
                x.setFacilitiesName(facilities.getFacilitiesName());
            });
            iHouseFacilitiesItemService.deleteHouseFacilitiesItemByHouseId(house.getHouseId());
            iHouseFacilitiesItemService.insertHouseFacilitiesItemList(facilitiesItemList);
        }
        return houseMapper.updateHouse(house);
    }

    /**
     * 批量删除房屋信息
     *
     * @param houseIds 需要删除的房屋信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteHouseByHouseIds(String[] houseIds) {
        House house = new House();
        house.setTenantId(TenantContext.getTenantId());
        house.setHouseIds(houseIds);
        List<House> houses = houseMapper.selectHouseByHouseIdsAndTenantId(house);
        if (houses.size() < houseIds.length) {
            throw new ServiceException("数据异常！");
        }
        // 检验房间是否有数据，没有则删除
        List<Order> orderList = orderService.selectOrderByHouseIds(houseIds);
        if (CollectionUtil.isNotEmpty(orderList)) {
            throw new ServiceException("房间有未完成的订单，请完成订单后再试");
        }
        List<HouseBill> houseBillList = houseBillService.selectHouseBillByHouseIds(houseIds);
        if (CollectionUtil.isNotEmpty(houseBillList)) {
            throw new ServiceException("房间有未付款的租客账单");
        }
        List<ProprietorBill> proprietorBillList = proprietorBillService.selectProprietorBillByHouseIds(houseIds);
        if (CollectionUtil.isNotEmpty(proprietorBillList)) {
            throw new ServiceException("房间有未付款的业主账单");
        }

        for (String houseId : houseIds) {
            houseMapper.softDeleteHouseByHouseIds(houseId);
            iSubHouseService.softDeleteSubordinateHouseByHouseIds(houseId);


            //     删除房屋配置
            HousingAllocation housingAllocation = iHousingAllocationService.selectHousingAllocationByHouseId(houseId);
            if (ObjectUtil.isNotEmpty(housingAllocation)) {
                iHousingAllocationService.softDeleteHousingAllocationByAllocationId(housingAllocation.getAllocationId());
            }
        }
        return 1;
    }

    /**
     * 删除房屋信息信息
     *
     * @param houseId 房屋信息主键
     * @return 结果
     */
    @Override
    public int deleteHouseByHouseId(String houseId) {
        return houseMapper.deleteHouseByHouseId(houseId);
    }

    @Override
    public House statistics() {

        House house = new House();

        //房间总数
        int houseNumber = houseMapper.selectHouseByHouseNumber(null, HouseConstants.SHARE_FLAT_NO, TenantContext.getTenantId());
        int subordinateHouseNumber = iSubHouseService.selectHouseByHouseNumber();
        house.setTotalHouseNumber(houseNumber + subordinateHouseNumber);


        //已出租房间总数
        int rentalHouseNumber = houseMapper.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, null, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateRentalHouseNumber = iSubHouseService.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, null,TenantContext.getTenantId());
        house.setRentalHouseNumber(rentalHouseNumber + subordinateRentalHouseNumber);

        //空置房间总数
        int vacancyHouseNumber = houseMapper.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_VACANCY, null, null, null, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateVacancyHouseNumber = iSubHouseService.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_VACANCY, null, null, null,TenantContext.getTenantId());
        house.setVacancyHouseNumber(vacancyHouseNumber + subordinateVacancyHouseNumber);

        //空置房间的比率
        double sum = (double) house.getVacancyHouseNumber() / house.getTotalHouseNumber();
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(2);//设置保留小数点后两位数
        house.setVacancyHousePercentage(house.getVacancyHouseNumber() == 0 ? "0.00%" : nt.format(sum));

        //线下房间总数
        int onlineDownHouseNumber = houseMapper.selectHouseCountByHouseState(null, null, null, HouseConstants.ONLINE_RENTAL_NO, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateOnlineDownHouseNumber = iSubHouseService.selectHouseCountByHouseState(null, null, null, HouseConstants.ONLINE_RENTAL_NO,TenantContext.getTenantId());
        house.setOnlineDownHouseNumber(onlineDownHouseNumber + subordinateOnlineDownHouseNumber);

        //已出租线下房间总数
        int onlineDownRentalHouseNumber = houseMapper.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, HouseConstants.ONLINE_RENTAL_NO, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateOnlineDownRentalHouseNumber = iSubHouseService.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, HouseConstants.ONLINE_RENTAL_NO,TenantContext.getTenantId());
        house.setOnlineDownRentalHouseNumber(onlineDownRentalHouseNumber + subordinateOnlineDownRentalHouseNumber);

        //线上房间总数
        int onlineUpHouseNumber = houseMapper.selectHouseCountByHouseState(null, null, null, HouseConstants.ONLINE_RENTAL_YES, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateOnlineUpHouseNumber = iSubHouseService.selectHouseCountByHouseState(null, null, null, HouseConstants.ONLINE_RENTAL_YES,TenantContext.getTenantId());
        house.setOnlineUpHouseNumber(onlineUpHouseNumber + subordinateOnlineUpHouseNumber);

        //已出租线上房间总数
        int onlineUpRentalHouseNumber = houseMapper.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, HouseConstants.ONLINE_RENTAL_YES, HouseConstants.SHARE_FLAT_NO,TenantContext.getTenantId());
        int subordinateOnlineUpRentalHouseNumber = iSubHouseService.selectHouseCountByHouseState(HouseConstants.HOUSE_STATE_LEASED, null, null, HouseConstants.ONLINE_RENTAL_YES,TenantContext.getTenantId());
        house.setOnlineUpRentalHouseNumber(onlineUpRentalHouseNumber + subordinateOnlineUpRentalHouseNumber);

        return house;
    }

    @Override
    public List<House> selectHouseListByInfo(House house) {
        return houseMapper.selectHouseListByInfo(house);
    }

    @Override
    public HouseStatus selectHouseStatus(House house) {
        return houseMapper.selectHouseStatus(house);
    }

    @Override
    public List<Map<String,Object>> countHouseState() {
        List<Map<String, Object>> houseStateList = new ArrayList<>();
        try {
            Class<Enum> clz = (Class<Enum>) Class.forName(HouseStateEnum.class.getName());
            Object[] objects = clz.getEnumConstants();
            Method getValue = clz.getMethod("getValue");
            Method getLabel = clz.getMethod("getLabel");
            Method getType = clz.getMethod("getType");
            Method getOtherType = clz.getMethod("getOtherType");
            Map<String, Object> totalMap = new HashMap<>();
            totalMap.put("value", "");
            totalMap.put("label", "全部");
            totalMap.put("type","");
            String tenantId = TenantContext.getTenantId();
            int totalNum = houseMapper.selectHouseCountByHouseState(null, null, null, null, null,tenantId);
            totalMap.put("number",totalNum);
            houseStateList.add(totalMap);
            for (Object object : objects) {
                Map<String, Object> stateMap = new HashMap<>();
                stateMap.put("value", getValue.invoke(object));
                stateMap.put("label", getLabel.invoke(object));
                stateMap.put("type",getType.invoke(object));
                int houseNum = houseMapper.selectHouseNumByHouseState(String.valueOf(getValue.invoke(object)),String.valueOf(getOtherType.invoke(object)),tenantId);
                stateMap.put("number",houseNum);
                houseStateList.add(stateMap);
            }
            return houseStateList;
        } catch (Exception e) {
            log.error("获取房屋常量失败：{}", e.getMessage(),e);
        }
        return houseStateList;

    }


    @Override
    public List<House> allHouseInfo() {
        House house = new House();
        house.setTenantId(TenantContext.getTenantId());
        return houseMapper.selectHouseList(house);
    }

    @Override
    public boolean checkHouse(House house) {
        int result = houseMapper.checkHouse(house);
        return result > 0;
    }

    @Override
    public Integer selectHouseByBuildingIdHouseNumber(String buildingId, String shareFlatType, String tenantId) {
        return houseMapper.selectHouseByBuildingIdHouseNumber(buildingId, shareFlatType, tenantId);
    }

    @Override
    public int selectHouseByHouseNumber(String estateId, String shareFlatType, String tenantId) {
        return houseMapper.selectHouseByHouseNumber(estateId,null, tenantId);
    }

    public int countHouseAll(String tenantId){
        return houseMapper.selectHouseCountByHouseState(null, null, null, null, null,tenantId);
    }

    @Override
    public List<House> conditionList(House house) {
        return houseMapper.conditionList(house);
    }

    @Override
    public List<House> selectHouseByHouseIds(List<String> houseIds) {
        return houseMapper.selectHouseByHouseIds(houseIds);
    }

    @Override
    public int insertHouseInfo(House house) {
        return houseMapper.insertHouse(house);
    }

    @Override
    public int editAllocation(House house) {
        House byHouseId = houseMapper.selectHouseByHouseId(house.getHouseId());
        if (!TenantContext.getTenantId().equals(byHouseId.getTenantId())) {
            throw new ServiceException("异常操作！");
        }
        if (house.getServiceCharge() == null) {
            throw new ServiceException("请输入账单服务费");
        }
        if (house.getServiceCharge().scale() > 1) {
            throw new ServiceException("账单服务费最多小数点后一位");
        }
        if (house.getServiceCharge().compareTo(new BigDecimal("100")) > 0) {
            throw new ServiceException("账单服务费比例不能大于100");
        }
        house.setUpdateTime(DateUtils.getNowDate());
        int i = houseMapper.updateHouse(house);
        if (i != 0) {
            HouseOperatingRecord record = new HouseOperatingRecord();
            record.setHouseId(house.getHouseId());
            record.setOperatingRecordContent("编辑了房屋信息");
            record.setOperatingRecordType(HouseOperatingRecord.OPERATING_RECORD_TYPE_ONE);
            record.setOperatingRecordId(house.getBizUserBusiness().getUserId());
            record.setOperatingRecordName(house.getBizUserBusiness().getUserName());
            record.setOperatingRecordPhone(house.getBizUserBusiness().getPhonenumber());
            iHouseOperatingRecordService.insertHouseOperatingRecord(record);
        }
        return i;
    }

    @Override
    public int updateHouseByDelFlag(String houseId) {
        return houseMapper.updateHouseByDelFlag(houseId);
    }

    @Override
    public int countHouseNumByTenantId(String tenantId) {
        return houseMapper.countHouseNumByTenantId(tenantId);
    }

    @Override
    public List<House> selectHousePage(House house) {
        return houseMapper.selectHousePage(house);
    }

    @Override
    public TableDataInfo pageByOrder(Order order) {
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(HttpStatus.SUCCESS);
        tableDataInfo.setMsg("查询成功");
        List<House> houseList = new ArrayList<>();
        if (StrUtil.isNotBlank(order.getOrderId())) {
            Order orderById = orderService.selectOrderById(order.getOrderId());
            if (StrUtil.equals(Order.ORDER_TYPE_SHORT_LEASE, orderById.getOrderType())) {
                //短租订单
                order.setOrderType(Order.ORDER_TYPE_SHORT_LEASE);
                order.setCheckInTime(orderById.getCheckInTime());
                Order linkedOrder = orderService.selectNewOrderByLinkedOrderId(orderById.getOrderId());
                if (ObjectUtil.isEmpty(linkedOrder)) {
                    order.setCheckOutTime(orderById.getCheckOutTime());
                } else {
                    order.setCheckOutTime(linkedOrder.getCheckOutTime());
                }
            } else if (StrUtil.equals(Order.ORDER_TYPE_LONG_LEASE, orderById.getOrderType())) {
                //长租订单
                order.setOrderType(Order.ORDER_TYPE_LONG_LEASE);
                order.setCheckInTime(orderById.getCheckInTime());
                order.setCheckOutTime(orderById.getCheckOutTime());
            }
        } else if (order.getCheckInTime() == null || order.getCheckOutTime() == null || StrUtil.isBlank(order.getOrderType())) {
            throw new ServiceException("请选择订单类型和入住时间");
        }
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = (pageDomain.getPageNum() - 1) * pageDomain.getPageSize();
        Integer pageSize = pageDomain.getPageSize();
        order.getParams().put("pageNum", pageNum);
        order.getParams().put("pageSize", pageSize);
        if (StrUtil.equals(Order.ORDER_TYPE_SHORT_LEASE, order.getOrderType())) {
            //短租订单
            int total = houseMapper.countHouseCountByShortLease(order);
            tableDataInfo.setTotal(total);
            if (total > 0) {
                houseList = houseMapper.selectHouseListByShortLease(order);
                tableDataInfo.setRows(houseList);
            }
        } else if (StrUtil.equals(Order.ORDER_TYPE_LONG_LEASE, order.getOrderType())) {
            //长租订单
            int total = houseMapper.countHouseCountByLongLease(order);
            tableDataInfo.setTotal(total);
            if (total > 0) {
                houseList = houseMapper.selectHouseListByLongLease(order);
                tableDataInfo.setRows(houseList);
            }
        }
        return tableDataInfo;
    }
}
